<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入黑名单号码"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="筛选日期">
        <el-form-item prop="createTimeStart">
          <el-date-picker
            v-model="queryParams.createTimeStart"
            type="date"
            placeholder="开始日期"
            value-format="YYYY-MM-DD"
            style="width: 120px"
            clearable
          />
        </el-form-item>

        <span class="ml10 mr10">-</span>
        <el-form-item prop="createTimeEnd">
          <el-date-picker
            v-model="queryParams.createTimeEnd"
            type="date"
            placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 120px"
            clearable
          />
        </el-form-item>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          @click="handleSearchDelete"
        >
          按条件删除
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="黑名单号码" align="center" prop="phone" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改黑名单号码对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="号码" prop="phones">
          <el-input
            v-model="form.phones"
            type="textarea"
            rows="5"
            placeholder="请输入黑名单号码"
          />
        </el-form-item>
        <el-form-item label="分隔符">
          <el-input
            v-model="form.separator"
            placeholder="号码之间的分隔符，默认为英文逗号"
          >
            <template #append>
              <el-button @click="handleSeparator">自动识别</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import * as api from '@/api/company/black-phone'
import { ref } from 'vue'

const { proxy } = getCurrentInstance()

const list = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

const data = reactive({
  form: {
    phones: '',
    separator: '',
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    phone: undefined,
  },
  rules: {
    phones: [{ required: true, message: '号码不能为空', trigger: 'blur' }],
  },
})

const { queryParams, form, rules } = toRefs(data)

getList()

/** 自动识别分隔符 */
function handleSeparator() {
  const str = form.value.phones
  let regex = /[^a-zA-Z0-9\u4e00-\u9fa5]/g
  let frequencies = {}
  let max = 0
  let mostFrequent = ''

  // 匹配字符串中特殊字符
  let specialChars = str.match(regex)

  for (let char of specialChars) {
    frequencies[char] = frequencies[char] ? frequencies[char] + 1 : 1
    if (frequencies[char] > max) {
      max = frequencies[char]
      mostFrequent = char
    }
  }

  form.value.separator = mostFrequent
}

/** 查询黑名单号码列表 */
function getList() {
  loading.value = true
  api.query(queryParams.value).then((response) => {
    list.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    phones: '',
    separator: '',
  }
  proxy.resetForm('formRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加黑名单号码'
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['formRef'].validate((valid) => {
    if (valid) {
      const phoneList = form.value.phones
        .split(form.value.separator || ',')
        .map((item) => item.trim())
        .filter(Boolean)
      api.add({ phoneList }).then(() => {
        proxy.$modal.msgSuccess('新增成功')
        open.value = false
        getList()
      })
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id ? [row.id] : ids.value
  proxy.$modal
    .confirm('是否确认删除黑名单号码编号为"' + id + '"的数据项？')
    .then(function () {
      const idsString = id.map((item) => item.toString())
      return api.remove(idsString)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

function handleSearchDelete() {
  proxy.$modal
    .confirm('是否确认删除黑名单号码编号为"' + id + '"的数据项？')
    .then(function () {
      return api.searchRemove(queryParams)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
</script>
